package org.celery.common.utils;

import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.OkHttpUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class IPUtil {

    /**
     * 获取IP地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    // 直接调用此方法
    public static String getCityInfo(String ip) {
        // 这里调用pconline的接口
        String urlStr = "https://apis.map.qq.com/ws/location/v1/ip";
        // 从http://whois.pconline.com.cn取得IP所在的省市区信息
        String result = OkHttpUtil.get(urlStr, new HashMap<String, String>() {{
            put("ip", ip);
            put("key", "AADBZ-5PJKX-GPL4I-TKSGL-5QS57-PAFWA");
        }});
        Map<String, Object> mapResult = JsonUtil.parse(result, Map.class);
        Integer status = (Integer) mapResult.get("status");
        if (status.equals(0)) {
            Map<String, Object> resultInfo = (Map<String, Object>) mapResult.get("result");
            Map<String, Object> adInfo = (Map<String, Object>) resultInfo.get("ad_info");
            if (Func.isNotEmpty(adInfo)) {
                String city = (String) adInfo.get("city");
                String province = (String) adInfo.get("province");
                String nation = (String) adInfo.get("nation");
                if (Func.isNotEmpty(city)) {
                    return city;
                } else if (Func.isNotEmpty(province)) {
                    return province;
                } else {
                    return nation;
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(getCityInfo("1.174.164.82"));
    }

}
